<?php
// 本类由系统自动生成，仅供测试用途
class ContractAction extends CommonAction {
	public function _filter(&$map) {
		$map['removed']=1;
		$subject = $_REQUEST ['subject'];
		$businesstype = $_REQUEST['businesstype'];
		if (! empty ( $subject )) {
			$map ['subject'] = array ('like',"%" . $subject . "%");
		}
	
		/* if(!empty($projectid)){
			if('2'==$projectid){
				$map ['projectid'] = array(' not in','0,1');
			}
			if('1'==$projectid){
				$map ['projectid'] = array('eq',$projectid);
			}
		}else{
			if('0'==$projectid){
				$map ['projectid'] = array('eq',$projectid);
			}
		} */
		if(!empty($businesstype)){
		$map ['businesstype'] = array('eq',$businesstype);
		}
		//   2013年5月3日需求变更，不在需要限制仅显示自己操作的记录
// 		if('1'!==$_SESSION [C ( 'USER_AUTH_KEY' )]){
// 			$map['userid']=$_SESSION [C ( 'USER_AUTH_KEY' )];
// 		}
		$this->assign ( 'subject', $subject );
	}
	public function _before_index() {
		$userid = $_SESSION [C ( 'USER_AUTH_KEY' )];
		$model = M ( "Contract" );
		/* $result = $this->isDepart ();
		// 默认管理员的id是1
		if ($result || $userid == 1) {
			$this->assign ( 'flag', 'flag' );
		}
		// 审批权限
		$apps = $this->isApprove ( $userid );
		if ($apps && $result || $userid == 1) {
			$this->assign ( 'aflag', 'aflag' );
		} */
		/* $this->assign ( 'userid', $userid );
		/* 业务提醒 */
		$model=D('Contract');
		//得到所有合同中的合同来源
		$projectlist=$model->field('projectid')->select();
		$business=D('Business');
		$buslist=$business->where('removed = 1')->field('id')->order('id desc')->select();
		for($i=0;$i<count($projectlist);$i++){
			$project[$i]=$projectlist[$i]['projectid'];//得到合同来源的projectid
		}
		for($j=0;$j<count($buslist);$j++){
			$buss[$j]=$buslist[$j]['id'];//得到业务的id
		}
		//比较业务和合同来源的差值
		if(!empty($buss)&&!empty($project)){
		$different=array_diff($buss,$project);
		}
		else
		{
			$different=$buss;
		}
		$difcount=count($different);
		/* dump($buss);
		dump($project);
		dump($different); */
		for($m=0;$m<=count($buss);$m++){
			if((int)$different[$m]!=0){
				$diflist[$m]=$business->where('id='.(int)$different[$m].' and removed = 1')->find();
			}			
			//echo (int)$different[$m];
		}
		//dump($diflist);
		$this->assign('difcount',$difcount);
		$this->assign('diflist',$diflist);
	}
	public function _before_add() {
		// 设置合同来源的id,为了方便从业务管理中拟定的合同
		// date('YmdHis');
		$id = $_REQUEST ['id'];
		$this->assign ( 'id', $id );
		$model = M ( "Contract" );
		$list = $model->select ();
		$this->getsubcompany();
		$this->assign ( 'list', $list );
	}
	
	/**
	 * 获得子公司的信息
	 * 
	 */
	
	public function getsubcompany()
	{
		//子公司信息
		$subcompany=M('Company');
		$sub=$subcompany->select();
		$this->assign('subcompany',$sub);
	}
	/**
	 * 获得对应的商品的信息
	 * 
	 */
	public function getcontroctgood()
	{
		//
		$cg=M('ControctGood');
		$sub=$cg->where('')->select();
		$this->assign('subcompany',$sub);
	}
	public function _before_edit() {
		$id = $_REQUEST ['id'];
		$model = M ( "Contract" );
		$type = $model->where ( 'id=' . $id )->getField ( 'type' );
		if ($type == 1) {
			$this->assign ( 'div1', 'block' );
			$this->assign ( 'div2', 'none' );
			$this->assign ( 'div3', 'none' );
		}
		if ($type == 2) {
			$this->assign ( 'div2', 'block' );
			$this->assign ( 'div1', 'none' );
			$this->assign ( 'div3', 'none' );
		}
		if ($type == 3) {
			$this->assign ( 'div3', 'block' );
			$this->assign ( 'div1', 'none' );
			$this->assign ( 'div2', 'none' );
		}
		
		$this->getsubcompany();
		$fileids=$model->where ( 'id=' . $id )->getField ( 'fileids' );
		if(!empty($fileids)){
		$model2=M('File');
		$list=$model2->where('id='.$fileids)->find();
		$filename=$list['path'].$list['savename'];
		$this->assign('filename',$filename);
		}
		
		$cn = M('ContractGood');
		$con = $cn->where('contractid='.$id)->select();
		$this->assign('cg',$con);
		
	}
	
	/**
	 * 填写的商品信息是否存在，如果不存在，就插入表中
	 */
	
	public function  insertgoods()
	{
		 $names=$_REQUEST['goodname'];
		 if(!empty($names))
		 {
	      $array= explode(",", $names);
	      foreach ($array as $name)
	      {
	      	$model=M('Goods');
	      	$list=$model->where('goodsname=\''.$name.'\'')->select();
	      	if(empty($list))
	      	{
	      		$data['goodsname']=$name;
	      		$model->add($data);	
	      	}
	      }
	    }
	}
	/**
	 * 填写的供应商，承运商信息是否存在，如果不存在，就插入表中
	 */
	
	public function  insertprcr( String $str)
	{
		$secondname=$_REQUEST['secondname'];
		
		if(!empty($secondname))
		{
				if($str=='Provider'){
					$model=M('Provider');
					$contactor = $_REQUEST['seconder'];
					$phone = $_REQUEST['secondphone'];
					$address = $_REQUEST['consignaddress'];
					$list=$model->where('providername=\''.$secondname.'\'')->select();
					if(empty($list))
					{
						$data['providername']=$secondname;
						$data['contactor']=$contactor;
						$data['phone']=$phone;
						$data['address']=$address;
						$Providerid=$model->add($data);
						return  $Providerid;
					}
				}else 
					if($str=='Carrier'){
					  $model=M('Carrier');
					  $contactor = $_REQUEST['seconder'];
					  $phone = $_REQUEST['secondphone'];
					  $address = $_REQUEST['consignaddress'];
					  $list=$model->where('carriername=\''.$secondname.'\'')->select();
					   if(empty($list))
					   {
						$data['carriername']=$secondname;
						$data['contactor']=$contactor;
						$data['phone']=$phone;
						$data['address']=$address;
						$Carrierid=$model->add($data);
						return $Carrierid;
					   }
				}
		}
	}
	
	/**
	 * 添加客户的供货信息
	 */
	public function addCustomergood($cusid,$lists){
		$moder = M('CustomerGood');
	    if(!empty($lists))
				{
					for($i=0;$i<count($lists);$i++){
						$dataCg ['customerid'] = $cusid;
						$dataCg ['product']=$lists[$i]['goodname'];//得到合同来源的projectid
						$dataCg ['supplyamount']=$lists[$i]['quality'];
						$dataCg ['hasexam'] = '0'; //已审批量初始化
				        $dataCg ['hassupply'] = '0'; //已经供货量初始化
				        $dataCg ['nosupply']= $lists[$i]['quality'];//未供货量
						
						$result=$moder->add($dataCg);
						if(!$result)
						{
							return false;
							//$this->ajaxReturn(1, '添加失败' ,300);
						}
					}
				}else{
					$goodname = $_POST['items_org_goodname'];
					$quality = $_POST['items_itemQuality'];
					$price = $_POST['items_itemPrice'];
					$totalprice = $_POST['items_itemTotalprice'];
					if(count($goodname)>=0){
						for($i=0;$i<count($goodname);$i++){
							$dataCg ['customerid'] = $cusid;
							$dataCg ['product'] = $goodname[$i];//商品名称
							$dataCg ['supplyamount'] = $quality[$i];//供货总量
							$dataCg ['hasexam'] = '0'; //已审批量初始化
							$dataCg ['hassupply'] = '0'; //已经供货量初始化
							$dataCg ['nosupply']= $quality[$i];//未供货量
							$result1 = $moder->add($dataCg);
							if($result1){
								return false;
							}
						}
					}
				}
				return true;
	}
	/**
	 * 修改客户的供货信息
	 */
	public function EditCustomergood($cusid,$lists){
		$Mcg = M ( 'CustomerGood' );
		//清空原有该客户供货信息
		$RDMcg = $Mcg->where('customerid='.$cusid)->delete();
		//新增新的供货信息
		$RaddCTG = $this->addCustomergood($cusid,$lists);
		return ($RaddCTG&&$RDMcg);
	}
	/**
	 * 更新客户的供货信息
	 */
	public function updatecustomergood($cusid){
		$Mcg = M ( 'CustomerGood' );
		$goodname = $_POST['goodname'];
		$quality = $_POST['quality'];
		$price = $_POST['price'];
		//清空原有该客户供货信息
		$RDMcg = $Mcg->where('customerid='.$cusid)->delete();
		//新增新的供货信息
		for($i=0 ; $i < count($goodname);$i++){
			$dataCg ['customerid'] = $cusid;
			$dataCg ['product'] = $goodname[$i];//商品名称
			$dataCg ['supplyamount'] = $quality[$i];//供货总量
			$dataCg ['hasexam'] = '0'; //已审批量初始化
			$dataCg ['hassupply'] = '0'; //已经供货量初始化
			$dataCg ['nosupply']= $quality[$i];//未供货量
			$RaddMcg = $Mcg->add($dataCg);
		}
		$RaddCusGood = $this->addCustomergood($cusid);
		return $RaddCusGood&&$RaddMcg&&$RDMcg;
	}
	public function insert() {
		$name=$this->getActionName();
		$model = D ($name);
		$model->startTrans();
		$this->insertgoods();
		$type = $_REQUEST['type'];
		$fileids=$this->getFileId();
		$_POST ['fileids']=$fileids; 
		$pid=$_REQUEST['pid'];
		$cmodel = M ( 'Customer' );
		$models=M('BusinessGood');
		$totalprice = $_POST['items_itemTotalprice'];
		$cusid = true;
		$RaddCusGood = true;
		$RCPT = true;
		$RCustome = true;
		$RECTG = true;
		$Providerid = true;
		$Carrierid = true;
		$result = true;
		$zje=0;
		if($totalprice){
			for($i=0;$i<count($totalprice);$i++){
				$zje+=$totalprice[$i];
			}
		}else{
			if($pid){
				$pg=$models->where('bussinessid='.$pid)->select();
				//dump($pg);
				for($i=0;$i<count($pg);$i++){
					$zje+=$pg[$i]['totalprice'];
				}
			}
		}
		//判断是合同类型，适当增加没有客户信息，承运商信息，供应商信息
		if('1'==$type){
		//添加客户信息
		
		$customerid = $cmodel->where ( 'customername=\''  . $_POST ['secondname'] . '\'' )->select ();
		//dump($customerid);
		//如果客户不存在，则信息自动添加到客户表,否则修改对应客户的信息
		if ($customerid == null) {
			$dataCustomer ['customerno'] = date ( 'YmdHis' );
			$dataCustomer ['customername'] = $_POST ['secondname'];
			$dataCustomer ['phone'] = $_POST ['secondphone'];
			$dataCustomer ['address'] = $_POST ['consignaddress'];
			$dataCustomer ['accountsno'] = $_POST ['accountno'];
	        $dataCustomer ['contractno'] = $_POST ['contractno'];//合同编号
	       
	        //总金额
	        $dataCustomer ['total'] = $zje;
	        $dataCustomer ['haspay'] = 0;
	        $dataCustomer ['nopay'] = $zje;
	        $_POST['totalprice']=$zje;
	        $_POST['apayment']=0;
	        $_POST['wpayment']=$zje;
	        $cusid = $cmodel->add ( $dataCustomer );
            if($cusid){
            	$_POST['secondid'] = $cusid;
            	if($pid){
            		$lists=$models->where('bussinessid='.$pid)->select();
            		$RaddCusGood = $this->addCustomergood($cusid, $lists);
            	}else{
            		$RaddCusGood = $this->addCustomergood($cusid);
            	}
            }else{
            	$model->rollback();
            	$this->ajaxReturn (1,'新增失败!',300);
            }
		}else{
			//总金额
			$dataCus ['total'] = $zje;
			$dataCus ['haspay'] = 0;
			$dataCus ['nopay'] = $zje;
			$dataCus ['removed'] = 1;
			$dataCus ['phone'] = $_POST ['secondphone'];
			$dataCus ['address'] = $_POST ['consignaddress'];
			$dataCus ['accountsno'] = $_POST ['accountno'];
			$dataCus ['contractno'] = $_POST ['contractno'];//合同编号
			$_POST['totalprice']=$zje;
			$_POST['apayment']=0;
			$_POST['wpayment']=$zje;
			$_POST['secondid'] = $customerid[0]['id'];
			$model2=M('CustomerPayment');
			$RCPT  = $model2->where('customerid='.$customerid[0]['id'])->delete();
			$RCustome = $cmodel->where ( 'id=\'' . $customerid[0]['id'] . '\'' )->save($dataCus);
			if($pid){
				$lists=$models->where('bussinessid='.$pid)->select();
				$RECTG = $this->EditCustomergood($customerid[0]['id'],$lists);
			}else{
				$RECTG = $this->EditCustomergood($customerid[0]['id']);
			}
			
		}
		}else if('2' == $type){
			$Providerid=$this->insertprcr('Provider');
			$_POST['secondid'] = $Providerid;
		}else if('3' == $type){
			$Carrierid=$this->insertprcr('Carrier');
			$_POST['secondid'] = $Carrierid;
		}
		
		if (false === $model->create ()) {
			$this->ajaxReturn(1, $model->getError () ,300);
		}
		$info=$this->getType($name);
		//保存当前数据对象
		$list=$model->add ();
		if ($list!==false) { //保存成功
			
			//拟定合同
			
			if(!empty($pid))
			{
				
				$lists=$models->where('bussinessid='.$pid)->select();
				if(!empty($lists))
				{
					for($i=0;$i<count($lists);$i++){
						$map['goodname']=$lists[$i]['goodname'];//得到合同来源的projectid
						$map['quality']=$lists[$i]['quality'];
						$map['price']=$lists[$i]['price'];
						$map['contractid']=$list;
						$map['alshipment']=0;
						$map['notshipment']=$lists[$i]['quality'];
						$map['totalprice']=$lists[$i]['totalprice'];
						$mod=M('ContractGood');
						$result=$mod->add($map);
						if($result==false)
						{
							$model->rollback();
							$this->ajaxReturn(1, '添加失败' ,300);
						}
					}
				}
			}
			//保存商品信息包括种类，吨数，单价，总额
			$this->AddMerchandise($list);
			$this->assign ( 'jumpUrl', Cookie::get ( '_currentUrl_' ) );
		} else {
			//失败提示
			$model->rollback();
			$this->insertLog('添加','操作'.$info.'编号为'.$list.'的数据失败');
			$this->ajaxReturn (1,'新增失败!',300);
		}
		if(($list!==false)&&($cusid!==false)&&($RaddCusGood!==false)&&($RCPT!==false)&&($result!==false)&&($Providerid!==false)&&($Carrierid!==false)){
			$model->commit();
			$this->insertLog('添加','操作'.$info.'编号为'.$list.'的数据成功');
			$this->ajaxReturn (1,'新增成功!',200);
		}else{
			$model->rollback();
			$this->ajaxReturn (1,'新增失败!',300);
		}
	}
	/**
	 * 保存商品信息包括种类，吨数，单价，总额
	 */
	public function AddMerchandise($list){
		$model = M('ContractGood');
		$goodname = $_POST['items_org_goodname'];
		$quality = $_POST['items_itemQuality'];
		$price = $_POST['items_itemPrice'];
		$totalprice = $_POST['items_itemTotalprice'];
		$moneytotal = 0;
		if(count($goodname)>=0){
			for($i=0 ; $i < count($goodname);$i++){
				$data['contractid']=$list;
				$data['goodname']=$goodname[$i];
				$data['quality']=$quality[$i];
				$data['price']=$price[$i];
				$data['totalprice']=$totalprice[$i];
				$data['alshipment']='0';
				$data['notshipment']=$quality[$i];
				$moneytotal+=$totalprice[$i];
				$model->add($data);
			}
		}
		return $moneytotal;
	}
	/**
	 * 修改商品信息
	 */
	public function updategood($goodid){
		$model = M('ContractGood');
		$goodname = $_POST['goodname'];
		$quality = $_POST['quality'];
		$price = $_POST['price'];
		$totalprice = $_POST['totalprice'];
		//返回修改后的商品金额总和
		$mt = 0;
		$id = $goodid;
		for($i=0 ; $i < count($goodname);$i++){
			$list=$model->where('id='.$id[$i])->find();
			$data['goodname']=$goodname[$i];
			$data['quality']=$quality[$i];
			$data['price']=$price[$i];
			$data['totalprice']=$totalprice[$i];
			$data['alshipment']=$list['alshipment'];
			$data['notshipment']=$quality[$i]-$list['alshipment'];
			$mt+=$totalprice[$i];
			$model->where('id='.$id[$i])->save($data);
		}
		return $mt;
	}
	public function _before_update() {
		$fileids=$this->getFileId();
		/* if(empty($fileids))
		{
			$this->ajaxReturn (1,'图片保存不正确!',300);
				
		} */
		$_POST ['fileids']=$fileids;
		$goodid = $_POST['goodid'];
		$this->insertgoods();
		$model = M ( 'Customer' );
		$model2 = M ( 'Contract' );
		$model2->startTrans();//开启事务
		$RupdateCus = true;
		$id=$_REQUEST['id'];
		$Con = $model2->find($id);
		if($Con['type']=='1'){
		$customerid = $model->where ( 'customername=\'' . $_POST ['secondname'] . '\' and removed=1' )->select ();
		if(!$customerid){
			$this->ajaxReturn(0,'已不存在该客户!',300);
		}else{
			$customername=$_POST ['secondname'];
			$old=$model2->where('id='.$id)->find();
			$oldfids=$old['fileids'];
			if(!empty($oldfids))
			{
				$filmodel=M('File');
				$filmodel->where('id='.$oldfids)->delete();
			}
			
			$RupdateCus = $this->updatecustomergood($customerid[0]['id']);
		}
		
	}
	$mt = $this->updategood($goodid);
	//计算修改后之前商品信息金额的差值
	$Dvalue = bcsub($mt,$Con['totalprice'],4);
	$moneytotal = $this->AddMerchandise($id);
	$status=$this->getres($id);
	if($status==0)
	{
		$status=101;
	}
	$_POST['totalprice'] = bcadd($moneytotal,$mt,4);
	$_POST['wpayment'] = bcadd($moneytotal,$Dvalue+$Con['wpayment'],4);
	$_POST ['status']=$status;
	if($RupdateCus!==false){
		$model2->commit();
	}else{
		$model2->rollback();
		$this->ajaxReturn(0,"修改失败！",300);
	}
}
public function getres($id)
{
	$cgood=M('ContractGood');

	$list=$cgood->where('contractid='.$id)->select();
	//$quality=0;
	if(!empty($list))
	{
		for ($i = 0; $i < count($list); $i++) {
			$quality+=$list[$i]['quality'];
			$alishiment+=$list[$i]['alshipment'];
		}
		if(!empty($quality)&&!empty($alishiment))
		{
			$precent=($alishiment/$quality)*100;
		}
		else
		{
			$precent=0;
		}
			
	}
	else
	{
		$precent=0;
	}
	return $precent;
}

	public function _before_foreverdelete()
	{
		$model = D ("Contract");
		$filem = M("File");
		$model->startTrans();//开启事务
		$id = $_REQUEST ['ids'];
	    $condition = explode ( ',', $id );
		$k = count ( $condition );
		for ( $j = 0; $j < $k; $j ++)
		{
		   // $fids=$model->where('id='.$condition[$j])->getField('fileids');
		   $fids=$filem->where('contractid='.$condition[$j])->select();
		   	if(!empty($fids))
		   	{
		   		$result=$filem->where('contractid='.$condition[$j])->delete();
		   		if($result==false)
		   		{
		   			$model->rollback();
		   			$this->ajaxReturn(1,'附件删除失败',300);
		   		}
		   	}else{
		     	$result = true;
		    }
		} 
		$ret = $this->deleteGoods($id);
		$ret1 = $this->deleteLog($id);
	    if(($result!==false)&&($ret!==false)&&($ret1!==false)){
	    	$model->commit();
	    }else{
	    	$model->rollback();
	    	$this->ajaxReturn(1,'删除失败',300);
	    }
	}
	
	public function deleteGoods($id)
	{
		//$id = $_REQUEST ['ids'];
		$model=M('ContractGood');
		$pk='contractid';
		if (isset ( $id )) {
			$condition = array ($pk => array ('in', explode ( ',', $id ) ) );
			$list = $model->where ( $condition )->select();
			if(count($list)>0){
				if (false !== $model->where ( $condition )->delete ()) {
					return true;
				} else {
					//$this->insertLog('彻底删除','操作'.$info.'编号为'.$id.'的数据失败');
					//$this->ajaxReturn (1,'删除失败!',300);
					return false;
				}
			}else{
				return true;
			}
		} else {
			return true;
			//$this->ajaxReturn (1,'进行删除操作出现非法操作!',200);
		}
		 
	}
	
	//删除合同记录的日志信息
	public function deleteLog($id)
	{
		//$id = $_REQUEST ['ids'];
		$model=M('ContractLog');
		$pk='contractid';
		if (isset ( $id )) {
			$condition = array ($pk => array ('in', explode ( ',', $id ) ) );
			$list = $model->where ( $condition )->select();
			if(count($list)>0){
				if (false !== $model->where ( $condition )->delete ()) {
					return true;
				} else {
					//$this->insertLog('彻底删除','操作'.$info.'编号为'.$id.'的数据失败');
					//$this->ajaxReturn (1,'删除失败!',300);
					return false;
				}
			}else{
				return true;
			}
		} else {
			//$this->ajaxReturn (1,'进行删除操作出现非法操作!',200);
			return true;
		}
	}
	/* // 判断当前用户是不是合同部门的
	// 默认合同部门的名字为contract
	public function isDepart() {
		$userid = $_SESSION [C ( 'USER_AUTH_KEY' )];
		$model = D ( 'Contract' );
		/**
		 * 如果把合同部门 的id定为1时
		 * sql语句定为select * from mlt_user where depid=1 and id=$userid
		 */
		/* $result = $model->query ( "select * from mlt_user a where a.depid='1' and a.id=" . $userid );
		if ($result == false) {
			return false;
		} else {
			return true;
		}
	} */
	// 判断合同管理中有审批权限的
	/* public function isApprove($userid) {
		$model = D ( 'Contract' );
		$rs = $model->query ( 'select * from mlt_access a ,mlt_role_user b where node_id=314 and pid=90 and level=3 and a.role_id=b.role_id and b.user_id=' . $userid );
		if ($rs == true) {
			return true;
		} else {
			return false;
		}
	} */ 
	
	// 当合同来源不是0的话，能查看业务来源
	public function lookup() {
		$id = $_REQUEST ['id'];
		$this->redirect ( 'Business/read', 'id=' . $id );
	}
	
	// 查找带回业务信息
	public function search() {
		$business = A ( 'Business' );
		$result = $business->index ();
		$this->assign ( 'list', $result );
		$this->display ();
	}
	
	// 审批
	public function approve() {
		$model = D ( 'Contract' );
		$id = $_REQUEST ['id'];
		$alshipment = $model->where ( 'id=' . $id )->getField ( 'alshipment' );
		$quality = $model->where ( 'id=' . $id )->getField ( 'quality' );
		$percent = ($alshipment / $quality) * 100;
		$this->assign ( 'percent', $percent );
		// $result=$model->where('id='.$id)->find();
		$result = $this->read ();
		$this->assign ( 'vo', $result );
		$this->display ();
	}
	/**
	 * 审批时添加客户供货信息
	 */
	/* protected function insertCustomerSup() {
		$model = M ( 'Contract' );
		$list = $model->where ( 'contractno=' . $_POST ['contractno'] )->find ();
		$data ['customername'] = $list ['secondname'];
		// $data ['orders'] = $_POST ['orders'];
		$data ['hassupply'] = $list ['alshipment'];
		$data ['nosupply'] = $list ['notshipment'];
		// $data ['newsupplytime'] = date ( 'Y-m-d H:i:s' );
		$data ['supplyamount'] = $list ['quality'];
		// $data['provider']=$list['provider'];
		$modelCus = M ( 'CustomerSupply' );
		$isExist = $modelCus->where ( 'contractno=' . $_POST ['contractno'] )->limit ( 1 )->select ();
		if ($isExist==null) {
			$data ['oldsupplytime'] = date ( 'Y-m-d H:i:s' );
		} else {
			$data ['oldsupplytime'] = $isExist ['oldsupplytime'];
		}
		$data ['hasexam'] = $_POST ['capacity'] + $isExist ['hasexam'];
		$custmoerSup = M ( 'CustomerSupply' );
		if ($custmoerSup->create ()) {
			if ($custmoerSup->where ( 'contractno=' . $_POST ['contractno'] )->select ()) {
				$custmoerSup->where ( 'contractno=' . $_POST ['contractno'] )->save ( $data );
			}
		}
	} */
	// 审批结果
	public function passapprove() {
		$model = D ( 'Contract' );
		$customerModel=M('Customer');
		$id = $_REQUEST ['id'];
		$payondelivery=$_REQUEST['payondelivery'];
		$status = $model->where ( 'id=' . $id )->getField ( 'status' );
		if ($status == 200) {
			$this->ajaxReturn ( 1, '该合同已放量完毕！', 300 );
		} else {
			$alshipment = $model->where ( 'id=' . $id )->getField ( 'alshipment' );//得到已放量吨数
			$quality = $model->where ( 'id=' . $id )->getField ( 'quality' );//得到此次放量吨数
			$userid = $_SESSION [C ( 'USER_AUTH_KEY' )];
			$capacity = $_REQUEST ['capacity'];
			$note = $_REQUEST ['note'];
			$data ['approveid'] = $userid;
			$data ['capacity'] = $capacity;
			/**
			 * 判断输入的放量值是否超过了余量
			 */
			$res = $quality - $alshipment;
			if ($res < $capacity || $capacity > $quality) {
				$this->ajaxReturn ( $res, '输入的放量数大于余量', 300 );
			}
			$data ['note'] = $note;
			$data ['alshipment'] = $alshipment + $capacity;
			$data ['notshipment'] = $quality - $alshipment - $capacity;
			$shipment = $alshipment + $capacity;
			if ($quality == $shipment) {
				$data ['status'] = 200;//如果放量完毕状态改为200
			} else {
				$data ['status'] = 101;
			}
			$data ['status'] = (($alshipment+$capacity) / $quality) * 100;
			$result = $model->where ( 'id=' . $id )->data ( $data )->save ();
			//当选择货到付款时更改对应客户的payondelivery状态
			if($payondelivery==1){
				$secondname=$model->where('id='.$id)->getField('secondname');
				$map['payondelivery']=1;
				$customerModel->where('customername=\''.$secondname.'\'')->save($map);
			}else{
				$secondname=$model->where('id='.$id)->getField('secondname');
				$map['payondelivery']=0;
				$customerModel->where('customername=\''.$secondname.'\'')->save($map);
			}
			//添加客户供货信息
			//$this->insertCustomerSup();
			$vo=$model->where('id='.$id)->find();
			$contractno = $model->where ( 'id=' . $id )->getField ( 'contractno' );
			if($vo['type']==1){
				
				$customer=$customerModel->query("select * from mlt_customer where customername='".$vo['secondname']."'");
				
				$datacustomer['hasexam']=$customer[0]['hasexam']+$capacity;
				$customerModel->where('customername=\''.$vo['secondname'].'\'')->save($datacustomer);
			}
			
			if ($result) {
				$this->ajaxReturn ( $result, '放量成功', 200 );
			} else {
				$this->ajaxReturn ( $result, '放量失败', 300 );
			}
		}
	}
	
	// 获得客户信息
	public function getcustomer() {
		$cust = A ( 'Customer' );
		$list = $cust->index ();
		$this->assign ( 'list', $list );
		$this->display ();
	}
	// 获得供应商信息
	public function getprovider() {
		$cust = A ( 'Provider' );
		$list = $cust->index ();
		$this->assign ( 'list', $list );
		$this->display ();
	}
	// 获得承运商信息
	public function getcarrier() {
		$cust = A ( 'Carrier' );
		$list = $cust->index ();
		$this->assign ( 'list', $list );
		$this->display ();
	}
	
	/**
	 * 获得商品信息
	 * 
	 */
	
	public function getgoods()
	{
		$goods=A('Goods');
		$list=$goods->index();
		$this->assign ( 'list', $list );
		$this->display ();
		
	}
	/**
	 * 显示合同进度
	 */
	public function progress() {
		$id = $_REQUEST ['id'];
		$model = M ( 'Contract' );
		$model1 = M ( 'ContractGood' );
		$Contract = $model->where ( 'id=' . $id )->find ();
		$alshipment = 0;
		$allgood = $model1->where ( 'contractid=' . $id )->select();
		for($i=0;$i<count($allgood);$i++){
			$alshipment+=$allgood[$i]['alshipment'];
			$notshipment+=$allgood[$i]['notshipment'];
		}
		$this->assign ( 'alshipment', $alshipment );
		$this->assign ( 'notshipment', $notshipment );
		$this->assign ( 'Contract', $Contract );
		$this->display ();
	}
	//高级检索
	public function retrieval(){
		$model=M('Customer');
		$Customer=$model->select();
		
		$model=M('Provider');
		$Provider=$model->select();
		$this->assign('provider',$Provider);
		$this->assign('customer',$Customer);
		$this->display();
	}
	
	//导出功能
	public function export(){	
		$model=D('Contract');		
		$contractno=$_REQUEST['contractno'];
		$start=$_REQUEST['start'];
		$end=$_REQUEST['end'];
		$type=$_REQUEST['type'];
		$businesstype=$_REQUEST['businesstype'];
		$secondname=$_REQUEST['secondname'];		
// 		dump($contractno);
// 		dump($start);
// 		dump($end);
// 		dump($type);
// 		dump($projectid);
// 		dump($secondname);		
		if(!empty($contractno)){
			$map['contractno']=array('eq',$contractno);
		}
		if(!empty($start)||!empty($end)){
			$map['contractdate'] = array('between',array($start,$end));
		}
		if(!empty($type)){
			$map['type']=array('eq',$type);
		}
		if(!empty($businesstype)){
			$map['businesstype']=array('eq',$businesstype);
		}
		if(!empty($secondname)){
			$map['secondname']=array('like',"%" . $secondname . "%");
		}
		$map['removed']=1;		
		$Contract=$model->where($map)->field('')->select();
		if(!empty($Contract))
		{
			for ($i=0;$i<count($Contract);$i++)
			{
			  $id=$Contract[$i]['id'];
			  $buslst[$i]['contractno']=$Contract[$i]['contractno'];
	  		  $buslst[$i]['firstname']=$Contract[$i]['firstname'];
			  $buslst[$i]['secondname']=$Contract[$i]['secondname'];
			  $buslst[$i]['seconder']=$Contract[$i]['seconder'];
			  $buslst[$i]['secondphone']=$Contract[$i]['secondphone'];
			  
			  $buslst[$i]['rateno']=$Contract[$i]['rateno'];
			  $buslst[$i]['accountno']=$Contract[$i]['accountno'];
			  $buslst[$i]['subject']=$Contract[$i]['subject'];
			  $buslst[$i]['goodname']=$this->getGoodsname($id);
			  $buslst[$i]['totalprice']=$this->getTotalPrice($id);
			  $buslst[$i]['deadline']=$Contract[$i]['deadline'];
			  $buslst[$i]['mainitem']=$Contract[$i]['mainitem'];
			  
			  $buslst[$i]['salesafteritem']=$Contract[$i]['salesafteritem'];
			  $buslst[$i]['validdae']=$Contract[$i]['validdae'];
			  $buslst[$i]['expiredate']=$Contract[$i]['expiredate'];
			  $buslst[$i]['signupuser']=$Contract[$i]['signupuser'];
			  $buslst[$i]['signuptime']=$Contract[$i]['signuptime'];
			  
			  $buslst[$i]['businesstype']=$Contract[$i]['businesstype'];
			  $buslst[$i]['consignaddress']=$Contract[$i]['consignaddress'];
			  $buslst[$i]['consignee']=$Contract[$i]['consignee'];
			  $buslst[$i]['clearform']=$Contract[$i]['clearform'];
		
	  		}
			}
		
		/* for($i=0;$i<count($Contract);$i++){
			if($Contract[$i]['projectid']=='0'){
				$Contract[$i]['projectid']="投标合同";
			}else{
				$Contract[$i]['projectid']="销售合同";
			}
		}
 */		$cname=date('Y-m-d');
		$map = array('合同编号','甲方','乙方','乙方人','乙方电话','税号','银行账号','合同标题','商品名称','金额','提货周期','主要条款','售后条款','生效日期','有效截止日期','签约人','签约时间','合同来源','收货地址','收货人','结算方式');
		$field=array('contractno','firstname','secondname','seconder','secondphone','rateno','accountno','subject','goodname','totalprice','deadline','mainitem','salesafteritem','validdae','expiredate','signupuser','signuptime','businesstype','consignaddress','consignee','clearform','secondname','contractamount','creator','consignee');
		 
		$this->phpexcel($buslst, $cname, $map,$field);
	}
	
	//获得商品的总金额
	public function getTotalPrice($id)
	{
		$bg=M('ContractGood');
		$list=$bg->query('select sum(totalprice) totalprice from mlt_contract_good where contractid='.$id);
		if(!empty($list))
		{
			$result=$list[0]['totalprice'];
			if(empty($result))
			{
				//return 0;
				$result=0;
			}
			return $result;
		}
		return 0;
	
	}
	//获得商品名称
	public function getGoodsname($id)
	{
		$bg=M('ContractGood');
		$list=$bg->where('contractid='.$id)->select();
		if(!empty($list))
		{
			for ($i = 0;  $i<count($list); $i++) {
				$result=$result.$list[$i]['goodname'].',';
			}
			$result=substr($result,0,strlen($result)-1);
		}
		return $result;
	}
	//业务提醒
	public function remind(){
		if($_REQUEST['draft']=='true'){
			$this->draft();
		}else{
			if($_REQUEST['insert']=='true'){
				$this->insert();
			}
		}
	   $userid = $_SESSION [C ( 'USER_AUTH_KEY' )];
		$model = M ( "Contract" );
		/* 业务提醒 */
		$model=D('Contract');
		//得到所有合同中的合同来源
		$projectlist=$model->field('projectid')->select();
		$business=D('Business');
		$buslist=$business->where('removed = 1')->field('id')->order('id desc')->select();
		for($i=0;$i<count($projectlist);$i++){
			$project[$i]=$projectlist[$i]['projectid'];//得到合同来源的projectid
		}
		for($j=0;$j<count($buslist);$j++){
			$buss[$j]=$buslist[$j]['id'];//得到业务的id
		}
		//比较业务和合同来源的差值
		if(!empty($buss)&&!empty($project)){
		$different=array_diff($buss,$project);
		}
		else
		{
			$different=$buss;
		}
		$difcount=count($different);
		/* dump($buss);
		dump($project);
		dump($different); */
		for($m=0;$m<=count($buss);$m++){
			if((int)$different[$m]!=0){
				$diflist[$m]=$business->where('id='.(int)$different[$m].' and removed = 1')->find();
			}			
			//echo (int)$different[$m];
		}
		//dump($diflist);
		$this->assign('difcount',$difcount);
		$this->assign('diflist',$diflist);
		$this->display();
	}
	public function _before_draft(){
		
		$id = $_REQUEST ['id'];
		$this->assign ( 'id', $id );
		$model = M ( "Contract" );
		$list = $model->select ();
		$this->getsubcompany();
		$this->assign ( 'list', $list );
	}	
	//拟定合同
	public function draft()
	{
		//业务的id
		$id=$_REQUEST['id'];
		$this->assign ( 'id', $id );
		$model = M ( "Contract" );
		$list = $model->select ();
		$this->getsubcompany();
		$this->assign ( 'list', $list );
		$model1=D('Business');
		$business=$model1->where('id='.$id)->find();
		$model2=M('BusinessGood');
		$goods=$model2->where('bussinessid='.$id)->select();
		$this->assign('bg',$goods);
		$this->assign('business',$business);
		$this->assign('id',$id);
		$this->display('draft');	
	}
	//文件上传
	public function upload() {		
		session_id($_POST['session_name']);
		session_start();
	    $this->getFileId();
	
	}

	//文件上传
	public function uploadFile(){
		//完成与thinkphp相关的，文件上传类的调用
		import('@.Org.UploadFile');//将上传类UploadFile.class.php拷到Lib/Org文件夹下
		$upload=new UploadFile();
		$upload->maxSize = 3145728 ; // 设置附件上传大小
		$upload->savePath='./Public/Uploads/'.date('Ymd').'/';//保存路径建议与主文件平级目录或者平级目录的子目录来保存
		$upload->allowExts=array('jpg','jpeg','png','gif','doc','zip','rar');//准许上传的文件类型
		//$upload->allowTypes=array("image/jpg");
		if($upload->upload()){
			$info=$upload->getUploadFileInfo();
			//dump($info);
			return $info;
		} else{
			if($upload->getErrorMsg()=="上传文件类型不允许"){
				$this->ajaxReturn( 1 , $upload->getErrorMsg(), 300);
			}//专门用来获取上传的错误信息的
		}
	}
	
	//保存合同附件
	public function getFileId()
	{
		$model = M("File");
		$fileinfo=$this->uploadFile();
		if(!empty($fileinfo)){
			$contractid=$_REQUEST['ids'];
			$data['name'] = $fileinfo[0]['name']; // 上传文件的原始名称
			$data['path'] ="/Uploads/".date('Ymd').'/'; // 上传文件的保存路径
			$data['extension'] = $fileinfo[0]['extension']; // 上传文件的后缀类型
			$data['size'] = ($fileinfo[0]['size']/1024).'Kb'; // 文件大小
			$data['savename']=$fileinfo[0]['savename'];
			//$data['type']=1;
			$data['state']=1;
			$data['uploadtime']=date('Ymd');
			$data['userid']= $_SESSION [C ( 'USER_AUTH_KEY' )];
			$data['username']=$_SESSION['username'];
			$data['contractid']=$contractid;
			$list=$model->add ($data);
			return $list;
		}
	}
	public function uploadify(){
		$type = $_REQUEST['type'];
		if('a'==$type){
			$this->upload();
		}else{
		$ids=$_REQUEST['ids'];
		$_SESSION['contractid']=$ids;
		$this->display();
		}
	}
	//下载附件页面
	public function downloadfile(){
		$type = $_REQUEST['type'];
		if('a'==$type){
			$this->download();
		}else{
		$id = $_REQUEST['ids'];
		$model = M('File');
		$currentpage=$_POST['pageNum'];//当前页数
		if(empty($currentpage))
		{
			$currentpage=1;
		}
		$pagenum=$_POST['numPerPage'];//每页显示的条数
		if(empty ($pagenum))
		{
			$pagenum=20;
		}
		$count = $model->where('contractid='.$id)->count();
		$list=$model->where('contractid='.$id)->page($currentpage,$pagenum)->select();

		$this->assign('list',$list);
		$this->assign('totalCount',$count);
		$this->assign('currentPage',$currentpage);
		$this->assign('id',$id);
		$this->assign("numPerPage",$pagenum);
		$this->display();
	}
	}
	//附件下载实现
	public function download(){
		$uploadPath = './Public/'; //设置文件上传路径，服务器上的绝对路径
		$id = $_GET['id']; //GET方式传到此方法中的参数id,即文件在数据库里的保存id.根据之查找文件信息。
		if($id == "")  //如果id为空而出错时，程序跳转到项目的Index/index页面。或可做其他处理。
		{
			echo '<script language="javascript">alert("没有此文件");</script>';
		}
			
		$file = D("File"); //利用与表file对应的数据模型类FileModel来建立数据对象。
		$map = array( 'id' => $id );
		$result = $file->where($map)->select();   //根据id查询到文件信息
			
		if($result==false) //如果查询不到文件信息而出错时，程序跳转到项目的Index/index页面,或可做其他处理
		{
			$this->redirect('index','Index',"APP_NAME",1);
		}else {
			$path=$result[0]['path'];//路径
			$savename = $result[0]['savename'];  //文件保存名
			$showname = $result[0]['name'];  //文件原名
			$filename = $uploadPath.$path.$savename; //完整文件名（路径加名字）
			$durl = $filename;
			$filename = iconv("utf-8","gbk",$showname);
			$file = @fopen($durl, 'r');
			header("Content-Type:text/html;charset=utf-8");
			header("Content-Type:application/force-download");
			header("Content-Type: application/octet-stream");
			header("Content-Type:application/download");
			header("Content-Transfet-Encoding:binary");
			header("Cache-Control:must-revalidate,post-check=0,pre-check=0");
			header("Accept-Ranges:    bytes");
			header("Accept-Length:    ".filesize($durl));
			header('Content-Disposition:    attachment;    filename="'.$filename.'"');
				
			echo   fread($file,filesize($durl));
			fclose($file);
		}
	}
	/**
	 * 删除合同中的商品信息
	 */
	public function gooddelete(){
		$cg = M('ContractGood');
		$id = $_REQUEST['conid'];
		$result = $cg->where('id='.$id)->delete();
		if($result){
			$this->ajaxReturn ( $result, '删除成功！', 200 );
		}else{
			$this->ajaxReturn ( $result, '删除失败！', 300 );
		}
	}
	public function read(){
		$id = $_REQUEST['id'];
		$model=M('Contract');
		$cn = M('ContractGood');
		$vo = $model->getById ( $id );
		$con = $cn->where('contractid='.$id)->select();
		$this->assign('cg',$con);
		$this->assign ( 'vo', $vo );
		$this->display();
	}
	
	
	public function addnote()
	{
		if("true"==$_REQUEST['insertNote']){
			$this->insertNote();
		}else{
			$id = $_REQUEST['id'];
			$this->assign('id',$id);
			$cg = M('Contract');
			$list=$cg->where('id='.$id)->getField('note');
			$this->assign('id',$id);
			$this->assign('note',$list);
			$this->display();
		}
	}
	public function insertNote()
	{
		$cg = M('Contract');
		$id = $_REQUEST['id'];
		$note=$_REQUEST['note'];
		
		//$list=$cg->where('id='.$id)->getField('note');
		$map['note']=$note;
		$result = $cg->where('id='.$id)->save($map);
		if($result){
			$this->ajaxReturn ( $result, '添加备注成功！', 200 );
		}else{
			$this->ajaxReturn ( $result, '添加备注失败！', 300 );
		}
	}
	
	
}